<script setup lang="ts">
    import type { FormInstance } from 'element-plus'
    import type { FormDesign } from './type'

    const props = defineProps<{ baseApi: string }>()

    const emit = defineEmits<{ (e: 'complete', id?: string): void }>()




    const {loadData, loading, model} = useDetail< FormDesign>(props.baseApi)

    const title = ref('')
    const visible = ref(false)

    defineExpose({
        open: (id ? : string) => {
            title.value = id ? '更新' : '新建'
            // 加载数据
            loadData(id)
            visible.value = true
        }
    })

    // 新建完是否清空表单继续填写
    const isContinueAdd = ref(false)

    //  表单
    const formRef = ref<FormInstance>()

    // 重置表单字段
    const resetFormFields = () => {
        formRef.value?.resetFields()
    }

    // 关闭对话框 自动重置表单字段
    watch(visible, value => !value &&  resetFormFields())

    const {submitting, submit} = useForm({
        baseApi: props.baseApi,
        successCallback(id) {
            emit('complete', id)
            visible.value = isContinueAdd.value
            if (isContinueAdd.value) resetFormFields()
        }
    })

    // 保存之前判断是否确认并继续添加
    const beforeSubmit = (value: boolean) => {
        isContinueAdd.value = value
        submit(model.value, formRef.value)
    }

</script>


<template>
    <el-dialog v-model="visible" width="60%" :title="title">
        <el-form ref="formRef" v-loading="loading" :model="model" label-width="80px">
            <el-row :gutter="18">
                    <el-col :span="12">
                            <el-form-item prop="formCode" label="表单编码">
                                    <el-input
                                            v-model="model.formCode"
                                            placeholder="请输入"
                                            clearable
                                    />
                            </el-form-item>
                    </el-col>
            </el-row>
        </el-form>

        <template #footer>
            <el-button @click="visible = false">取消</el-button>
            <el-button v-if="!model.id" type="primary" :loading="submitting" @click="beforeSubmit(true)">
                保存并继续
            </el-button>
            <el-button type="primary" :loading="submitting" @click="beforeSubmit(false)">保存</el-button>
        </template>
    </el-dialog>
</template>

<style scoped>
    .option {
        display: flex;
        justify-content: space-between;

        .ext {
            font-size: var(--el-font-size-extra-small);
            color: var(--el-text-color-secondary);
        }
    }
</style>